package microservice.demo.servicecomb.course.helloservice.exceptionconverter;

import javax.ws.rs.core.Response.Status;

import org.apache.servicecomb.swagger.invocation.Response;
import org.apache.servicecomb.swagger.invocation.SwaggerInvocation;
import org.apache.servicecomb.swagger.invocation.exception.CommonExceptionData;
import org.apache.servicecomb.swagger.invocation.exception.ExceptionToProducerResponseConverter;
import org.apache.servicecomb.swagger.invocation.exception.InvocationException;

import microservice.demo.servicecomb.course.helloservice.endpoint.DemoException;

public class DemoExceptionConverter implements ExceptionToProducerResponseConverter<DemoException> {
  /**
   * 该方法的返回值表明 DemoExceptionConverter 处理 DemoException 及其子类的异常。
   */
  @Override
  public Class<DemoException> getExceptionClass() {
    return DemoException.class;
  }

  /**
   * 当业务代码抛出的 DemoException 被捕获，会传入该方法进行处理。
   * @param swaggerInvocation 本次业务调用相关的信息
   * @param e 被捕获的异常
   * @return 转换后的响应消息，将会发送给调用方
   */
  @Override
  public Response convert(SwaggerInvocation swaggerInvocation, DemoException e) {
    return Response.producerFailResp(
        new InvocationException(Status.BAD_REQUEST,
            new CommonExceptionData(
                swaggerInvocation.getInvocationQualifiedName() + " gets illegal param: " + e.getMessage())));
  }
}
